<?php
class EWebby_Event {
	private $_eventHandlers = array();

	public function addListener($eventHandler) {
		if( is_array($this->_eventHandlers) ) {
			$this->_eventHandlers[] = $eventHandler;
		} else {
			throw new EWebby_Exception('add listener was failed');
		}
	}

	public function removeListener($eventHandler) {
		if( is_array($this->_eventHandlers) ) {
			for($i=0,$count=count($this->_eventHandlers); $i<$count; $i++) {
				if( $this->_eventHandlers[$i] === $eventHandler ) {
					unset( $this->_eventHandlers[$i] );
					return;
				}
			}
		}
		
		throw new EWebby_Exception('event listener does not exists');
	}
	
	public function dispatchEvent($sender, $eventArgs) {
		if( is_array($this->_eventHandlers) ) {
			for($i=0,$count=count($this->_eventHandlers); $i<$count; $i++) {
				if( !isset($this->_eventHandlers[$i]) ) {
					continue;
				}
				
				$curEventHandler = $this->_eventHandlers[$i];
				if( $curEventHandler != null
					&& $curEventHandler instanceof EWebby_EventHandler) {
					$curEventHandler->call($sender, $eventArgs);
				}
			}
		}
	}
}